<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'material:app:pmMaterialappvouchChecks:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #pmMaterialappvouchCheckList>
        <BasicTable
          @register="registerPmMaterialappvouchCheckTable"
          @row-click="handlePmMaterialappvouchCheckRowClick"
        />
        <a-button
          class="mt-2"
          @click="handlePmMaterialappvouchCheckAdd"
          v-auth="'material:app:pmMaterialappvouchChecks:edit'"
        >
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
      </template>
    </BasicForm>
    <template #footer>
      <BpmButton
        v-model:bpmEntity="record"
        bpmEntityKey="id"
        formKey="Flow_MaterialAppvouch_check"
        completeText="提交"
        :loading="loadingRef"
        :auth="'oa:oaLeave:edit'"
        @complete="handleSubmit"
        @success="handleSuccess"
        @close="closeDrawer"
      />
    </template>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsMaterialAppPmMaterialappvouchChecksForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    PmMaterialappvouchChecks,
    pmMaterialappvouchChecksSave,
    pmMaterialappvouchChecksForm,
  } from '/@/api/material/app/pmMaterialappvouchChecks';
  import { BpmButton } from '/@/components/Bpm';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('material.app.pmMaterialappvouchChecks');
  const { showMessage } = useMessage();
  const record = ref<PmMaterialappvouchChecks>({} as PmMaterialappvouchChecks);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增库领数据纠正') : t('编辑库领数据纠正'),
  }));

  const loadingRef = ref(false);

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('主表ID'),
      field: 'parentId',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      required: true,
    },
    {
      label: t('项目编号'),
      field: 'projectno',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      required: true,
    },
    {
      label: t('材料编号'),
      field: 'mcode',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      required: true,
    },
    {
      label: t('原始库领量'),
      field: 'oldStQty',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      rules: [
        { required: true },
        { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') },
      ],
    },
    {
      label: t('实际库领量'),
      field: 'sjKlQty',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      rules: [
        { required: true },
        { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') },
      ],
    },
    {
      label: t('备注信息'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 255,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('图片上传'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'pmMaterialappvouchChecks_image',
        uploadType: 'image',
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('库领数据纠正'),
      field: 'pmMaterialappvouchCheckList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'pmMaterialappvouchCheckList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerPmMaterialappvouchCheckTable, pmMaterialappvouchCheckTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handlePmMaterialappvouchCheckDelete.bind(this, record),
          },
          auth: 'material:app:pmMaterialappvouchChecks:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setPmMaterialappvouchCheckTableData(_res: Recordable) {
    pmMaterialappvouchCheckTable.setColumns([
      {
        title: t('来源ID'),
        dataIndex: 'sourceId',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: true,
      },
      {
        title: t('备注信息'),
        dataIndex: 'remarks',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 500,
        },
        editRule: false,
      },
      {
        title: t('创建人名称'),
        dataIndex: 'createByName',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('更新人名称'),
        dataIndex: 'updateByName',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
    ]);
    pmMaterialappvouchCheckTable.setTableData(record.value.pmMaterialappvouchCheckList || []);
  }

  function handlePmMaterialappvouchCheckRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handlePmMaterialappvouchCheckAdd() {
    pmMaterialappvouchCheckTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handlePmMaterialappvouchCheckDelete(record: Recordable) {
    pmMaterialappvouchCheckTable.deleteTableDataRecord(record);
  }

  async function getPmMaterialappvouchCheckList() {
    let pmMaterialappvouchCheckListValid = true;
    let pmMaterialappvouchCheckList: Recordable[] = [];
    for (const record of pmMaterialappvouchCheckTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        pmMaterialappvouchCheckListValid = false;
      }
      pmMaterialappvouchCheckList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of pmMaterialappvouchCheckTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      pmMaterialappvouchCheckList.push({
        ...record,
        status: '1',
      });
    }
    if (!pmMaterialappvouchCheckListValid) {
      throw { errorFields: [{ name: ['pmMaterialappvouchCheckList'] }] };
    }
    return pmMaterialappvouchCheckList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await pmMaterialappvouchChecksForm(data);
    record.value = (res.pmMaterialappvouchChecks || {}) as PmMaterialappvouchChecks;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setPmMaterialappvouchCheckTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      data.bpm = record.value.bpm; // 流程信息
      data.status = record.value.status; // 提交状态
      loadingRef.value = true;
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.pmMaterialappvouchCheckList = await getPmMaterialappvouchCheckList();
      // console.log('submit', params, data, record);
      const res = await pmMaterialappvouchChecksSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }
</script>
